package com.yx.system.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.sun.tools.internal.xjc.reader.dtd.TDTDReader;
import com.yx.common.annotation.Log;
import com.yx.common.annotation.LoginUser2;
import com.yx.common.utils.PageUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.common.validator.Assert;
import com.yx.modules.api.annotation.LoginUser;
import com.yx.modules.api.entity.TbRewardRecord;
import com.yx.modules.api.entity.TbUser;
import com.yx.modules.api.entity.TbVolume;
import com.yx.modules.api.service.*;
import com.yx.system.dto.BookDto;
import com.yx.system.dto.TbRwardBookDto;
import com.yx.system.entity.*;
import com.yx.system.service.*;
import com.yx.utils.DateUtil;
import com.yx.utils.UidUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 书籍控制器
 */
@RestController
@RequestMapping("/sys/book")
public class TdBookController2{

    @Autowired
    private TdBookService tdBookService;

    @Autowired
    private TdSectionService tdSectionService;

    @Autowired
    private TdCategoryService tdCategoryService;

    @Autowired
    private TdClassificationService tdClassificationService;

    @Autowired
    private TbVolumeService tbVolumeService;

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    //图书评论
    private TbBookCommentService tbBookCommentService;

    @Autowired
    //图书点赞记录
    private TbBookRecommendRecordService tbBookRecommendRecordService;

    @Autowired
    //图书点击记录
    private TbClickService tbClickService;

    @Autowired
    //图书评论点赞记录
    private TbCommentDianzanRecordService tbCommentDianzanRecordService;

    @Autowired
    //图书打分记录
    private TbGradeRecordService tbGradeRecordService;

    @Autowired
    //图书打赏记录
    private TbRewardRecordService tbRewardRecordService;

    @Autowired
    private TbKwordPriceService tbKwordPriceService;



    /**
     * 按ID查询书籍
     *
     * @return
     */
    @RequestMapping("/findById/{id}")
    @RequiresPermissions("sys:book:findById")
    public R findById(@PathVariable("id") int id) {
        TdBook tdBook = tdBookService.selectByPrimaryKey(id);
        return R.ok().put("book", tdBook);
    }

    /**
     * 按条件查询所有
     * <p>
     * 查询所有（按条件查询）
     * 是否新书 isnew;
     * 是否推荐 isrecommend;
     * 是否热门 ishot;
     * 是否连载 iscontinuous;
     * 是否删除 isdelete;
     *
     * @return
     */
    @RequestMapping("findAllByCondition")
    @RequiresPermissions("sys:book:findAllByCondition")
    public R findAllByCondition(@RequestParam Map<String, Object> map,@LoginUser2 SysUser sysUser) {

        Query query = new Query(map);
        if (sysUser.getIdentity()!=0){
            TbUser user = tbUserService.findByMobile(sysUser.getUsername());
            Assert.isNull(user,"查无此用户");
            query.put("authorCode",user.getUuid());
        }
        Page<TdBook> pageUtil = new Page<TdBook>(query.getPage(), query.getLimit());
        Page<TdBook> page = tdBookService.queryPageList(pageUtil, query);
        return R.ok().put("page", page);
    }

    /**
     * 查询所有数据
     * @return
     */
    @PostMapping("findAll")
    public R findAll(){
        List<TdBook> list = tdBookService.queryAll();
        return R.ok().put("list",list);
    }


    /**
     * 新增或修改
     *
     * @return
     */
    @PostMapping("saveOrUpdate")
    @RequiresPermissions("sys:book:saveOrUpdate")
    public R saveOrUpdate(@RequestBody TdBook tdBook, @LoginUser2 SysUser sysUser) {
        Assert.isBlank(tdBook.getBookname(),"书名不能为空");
        Assert.isBlank(tdBook.getPicurl(),"图书封面不能为空");
        Assert.isNull(tdBook.getCategoryid(),"图书所属分类不能为空");
        Assert.isBlank(tdBook.getIntroduction(),"图书简介不能为空");
        Assert.isBlank(tdBook.getSource(),"图书来源不能为空");
        if (sysUser.getIdentity()==1 && tdBook.getIspay()){
            return R.error("签约作者才能收费");
        }
        TbUser user = tbUserService.findByMobile(sysUser.getUsername());
        if (tdBook.getId() == null) {
            //存入书籍
            tdBook.setIsdelete(false);
            //设置点击数初始化
            tdBook.setChecknum(0);
            //设置分类
            TdCategory tdCategory = tdCategoryService.selectByPrimaryKey(tdBook.getCategoryid());
            tdBook.setCategoryname(tdCategory.getCategoryyname());
            //初始化二级分类信息（暂无用）
            tdBook.setClassificationid(0);
            tdBook.setClassificationname("0");
            tdBook.setBooktype(0);
            if (user!=null){
                tdBook.setAuthorCode(user.getUuid());
                tdBook.setAuthorName(user.getNickname());
                tdBook.setIsgongting(false);
                tdBook.setIsjingxuan(false);
                tdBook.setIsqihuan(false);
                tdBook.setIsremen(false);
                tdBook.setIssanjie(false);
                tdBook.setIsserialize(true);
                tdBook.setIswuxia(false);
                tdBook.setIsxianjie(false);
                tdBook.setIsxianyan(false);
                tdBook.setIspay(false);
            }else {
                //平台上传书籍，默认作者code为O
                tdBook.setAuthorCode("0");
            }
            //设置创建时间和更新时间
            tdBook.setCreatedate(new Date());
            tdBook.setUpdatedate(new Date());
            //生成随机唯一标示
            tdBook.setBookno(UUID.randomUUID().toString());
            //初始化数据
            tdBook.setGrade(Double.valueOf(0));
            tdBook.setGradeNumber(0);
            tdBook.setGradeSum(Double.valueOf(0));
            tdBook.setLikeCount(0);
            tdBook.setCommentGirlCount(0);
            tdBook.setCommentBoyCount(0);
            tdBook.setCollectionCount(0);
            tdBook.setCommentCount(0);
            tdBook.setRewardMoney(0);
            tdBook.setRewardCount(0);
            tdBook.setChecknum(0);
            tdBook.setSell(0);
            tdBook.setFontCount(0);
            tdBook.setSectionNumber(0);
            tdBook.setWordType(0);
            tdBook.setBooknum((int) Math.random());
            tdBook.setSubscibeMoney(0);
            tdBook.setGuarantee(Double.valueOf(0));
            tdBook.setGameSubscribeCount(0);
            tdBook.setGameClickCount(0);
            tdBookService.insert(tdBook);
            //初始化图书的卷对象
            TbVolume tbVolume = new TbVolume();
            tbVolume.setBookId(tdBook.getId());
            tbVolume.setCreateDate(new Date());
            tbVolume.setUpdateDate(new Date());
            tbVolume.setVolumeName("第一卷");
            tbVolume.setBookName(tdBook.getBookname());
            //更新卷信息
            tbVolumeService.save(tbVolume);
        } else {
            tdBook.setUpdatedate(new Date());
            tdBookService.updateByPrimaryKey(tdBook);
        }
        return R.ok();
    }

    /**
     * 删除 (软删除)
     *
     * @return
     */
    @Log("删除小说")
    @RequestMapping("delete")
    @RequiresPermissions("sys:book:delete")
    public R delete(@RequestBody Integer[] ids) {
        Thread thread = new Thread(){
            public void run(){
                tdBookService.delete(ids);
            }
        };
        thread.start();
        return R.ok("正在清理数据，请在几分钟后刷新查看");
    }

    /*
    * 获取后台图书打赏列表
    */
    @RequestMapping("rewardList")
    public R getRewardList(@LoginUser2 SysUser sysUser,@RequestParam Map<String, Object> params){
        if (sysUser.getIdentity()==0){
            return R.error("作者才有权查看图书评论");
        }
        //查询对应的用户
        TbUser tbUser = tbUserService.findByMobile(sysUser.getUsername());
        if (tbUser.getIdentity()==0){
            return R.error("用户的身份不是作者");
        }
        //查询列表数据
        Query query = new Query(params);
        query.put("authorCode",tbUser.getUuid());
        List<TdBook> tdBooks = tdBookService.queryList(query);
        int total = tdBookService.queryTotal(query);
        //组装返回的DTO集合
        List<TbRwardBookDto> tbRwardBookDtos = new ArrayList<>();
        //循环图书对象
        for (TdBook tdBook:tdBooks){
            //初始化数据传输对象
            TbRwardBookDto tbRwardBookDto = new TbRwardBookDto();
            //初始化一个查询参数
            Date date = new Date();
            Map<String,Object> map = new HashMap<>();
            map.put("bookId",tdBook.getId());
            map.put("rewardYear", DateUtil.getYear(date));
            map.put("rewardMonth",DateUtil.getMonth(date));
            //初始化统计的值
            Integer rewardMonth = 0;
            Integer rewardDay = 0;
            //计算月统计
            rewardMonth = tbRewardRecordService.findByCondition(map);
            map.put("rewardDay",DateUtil.getDay(date));
            //计算日统计
            rewardDay = tbRewardRecordService.findByCondition(map);
            //注值进入DTO
            tbRwardBookDto.setRewardDay(rewardDay);
            tbRwardBookDto.setRewardMonth(rewardMonth);
            tbRwardBookDto.setTdBook(tdBook);
            tbRwardBookDtos.add(tbRwardBookDto);
        }

        PageUtils pageUtil = new PageUtils(tbRwardBookDtos, total, query.getLimit(), query.getPage());

        return R.ok().put("page",pageUtil);
    }


    /*
    * 查看具体图书的打赏记录
    */
    @RequestMapping("reward")
    @RequiresPermissions("sys:book:reward")
    public R getReward(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<TbRewardRecord> tbRewardRecords = tbRewardRecordService.queryList(query);
        int total = tbRewardRecordService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(tbRewardRecords, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }


    /*
    * 图书定价
    */
    @RequestMapping("pricing")
    public R bookPricing(Integer start,Integer kwordPriceId,Integer bookid){
        Assert.isNull(start,"请选择开始收费章节");
        //查询book
        TdBook tdBook = tdBookService.selectByPrimaryKey(bookid);
        Assert.isNull(tdBook,"未查询到相关图书");
        //找到对应的价格
        TbKwordPrice tbKwordPrice = tbKwordPriceService.queryObject(kwordPriceId);
        Assert.isNull(tbKwordPrice,"查询到定价出错");
        //根据图书找到所有章节
        List<TdSection> tdSections = tdSectionService.findByBookid(tdBook.getId());
        if (tdSections.size()<=start){
            return R.error("开始付费章节大于了总章节数");
        }
        Thread thread = new Thread(){
            public void run(){
                tdBookService.pricing(tdBook,tdSections,tbKwordPrice,start);
            }
        };
        thread.start();
        return R.ok("章节定价可能需要一点时间，请稍后刷新页面查看");
    }

}
